<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="客户名称" prop="title1">
        <el-input v-model.trim="queryParams.title1" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery"
          @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="报价单名称" prop="title2" label-width="100px">
        <el-input v-model="queryParams.title2" placeholder="请输入报价单名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="报价单编号" prop="title3" label-width="100px">
        <el-input v-model="queryParams.title3" placeholder="请输入报价单编号" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <div>
        <el-form-item label="报价时间">
          <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
            start-placeholder="开始日期" end-placeholder="结束日期" @change="changeTime" @clear="clearTime"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :data="roleList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="cumtomID" width="400" />
      <el-table-column label="报价单名称" align="center" prop="queryContent" width="400" />
      <el-table-column label="报价单编号" align="center" prop="queryCode" width="200" />
      <el-table-column label="报价时间" align="center" prop="queryCode" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="160px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="openQuoteDialog(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
    <!-- 使用新的对话框组件 -->
    <QuoteDialog :dialogVisible="dialogVisible" :dataList="dataList" @handleUpdate="handleUpdate"
      @update:dialogVisible="dialogVisible = $event" @submitForm="handleSubmitForm" />
    <!-- 修改询价弹窗--单项信息 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="rowForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input v-model.trim="rowForm.billName" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格">
              <el-input v-model.trim="rowForm.billSpecifications" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号">
              <el-input v-model.trim="rowForm.billTypes" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量">
              <el-input v-model.trim="rowForm.billRemaining" type="number" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位">
              <el-input v-model.trim="rowForm.billUnit" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="采购备注">
              <el-input v-model.trim="rowForm.billManufacturer" disabled placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成本" prop="unitCost">
              <el-input-number v-model="rowForm.unitCost" step-strictly :max="100000000" @change="UpdateSellingPrice2">
                <template #suffix>
                  <span>分</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率" prop="taxRate">
              <el-input-number v-model="rowForm.taxRate" :step="0.1" :precision="4" :max="100000000"
                @change="UpdateSellingPrice2">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="利润率" prop="profitRate">
              <el-input-number v-model="rowForm.profitRate" :step="0.1" :precision="4" :max="100000000"
                @change="UpdateSellingPrice2">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣率" prop="discount">
              <el-input-number v-model="rowForm.discount" :step="0.1" :precision="4" :max="100000000"
                @change="UpdateSellingPrice2">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠" prop="preferential">
              <el-input-number v-model="rowForm.preferential" step-strictly :max="100000000"
                @change="UpdateSellingPrice2">
                <template #suffix>
                  <span>分</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价">
              <el-input-number v-model="rowForm.unitPrice" :disabled="true" :precision="3" :max="100000000">
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import { GetTenantPageList, AddTenant, EditTenant, DelTenant } from "@/api/system/tenant";
import { useInfoStore } from '@/store/modules/info.js'
import QuoteDialog from './components/QuoteDialog.vue';
const userInfo = useInfoStore();
const dialogVisible = ref(false);
const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const roleList = ref([]);
const dataInfo = ref([]);
const dataList = ref([]);
const data_Id = ref(null);//询价记录id
const rowForm = ref();
const rowDisabled = ref(false);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);


const data = reactive({
  form: {
    tenantName: null,
    tenantDoMain: null,
    tenantDes: null,
    tenantOrders: 0,
    id: null
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    title1: null,
    title2: null,
    title3: null,
    dt1: null,
    dt2: null,
  },
  rules: {
    billName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    billRemaining: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    billTypes: [{
      validator: (rule, value, callback) => {
        if (!rowForm.value.billTypes && !rowForm.value.billSpecifications) {
          callback(new Error('规格和型号至少填写一项'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    billSpecifications: [{
      validator: (rule, value, callback) => {
        if (!rowForm.value.billTypes && !rowForm.value.billSpecifications) {
          callback(new Error('规格和型号至少填写一项'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    unitCost: [{ required: true, message: "成本不能为空", trigger: "blur" }],
    taxRate: [{ required: true, message: "税率不能为空", trigger: "blur" }],
    profitRate: [{ required: true, message: "利润率不能为空", trigger: "blur" }],
    discount: [{ required: true, message: "折扣率不能为空", trigger: "blur" }],
    preferential: [{ required: true, message: "优惠不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

function UpdateSellingPrice2() {
  // 成本监听逻辑
  if (rowForm.value.unitCost >= 5000) {
    rowForm.value.profitRate = 1.33;
  } else {
    rowForm.value.profitRate = 1.35;
  }
  const { unitCost, taxRate, profitRate, discount, preferential } = rowForm.value;
  let price1Show = (unitCost * taxRate * profitRate * discount - preferential) / 100;
  // 保留三位小数，最后一位四舍五入
  rowForm.value.unitPrice = parseFloat(price1Show.toFixed(3));
}
/** 时间转换 */
function changeTime(val) {
  if (val) {
    queryParams.value.dt1 = val[0];
    queryParams.value.dt2 = val[1];
    getList();
  }
}
// 重置时间
function clearTime() {
  queryParams.value.dt1 = null;
  queryParams.value.dt2 = null;
  getList();
}

// 打开对话框的方法
function openQuoteDialog(row) {
  data_Id.value = row.id;
  proxy.quote_API.GetPriceUnquirylistByBatch({queryBatch: row.queryBatch}).then(response => {
    dataList.value = response.data || [];
    dialogVisible.value = true;
  });
}

function handleUpdate(row) {
  // 处理修改逻辑
  proxy.quote_API.GetMaterial({
    id: row.materialID,
  }).then(response => {
    rowForm.value = { 
      ...row,
      unitCost: response.data.price.cost || 0,//成本
      taxRate: response.data.price.taxRate || 0,//税率
      profitRate: response.data.price.profitRate || 0,//利润率
      discount: response.data.price.discount ||  0,//折扣率
      preferential: response.data.price.preferential || 0,//优惠
      unitPrice: response.data.price.price1Show || 0,//单价
     }; // 使用对象的副本避免引用问题
    open.value = true;
    title.value = "修改物料数据";
  });
}

/** 提交按钮-更新数据 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
       // 修改物料--且更新报价
       proxy.quote_API.EditMaterialPrice({
        cost: rowForm.value.unitCost,
        profitRate: rowForm.value.profitRate,
        taxRate: rowForm.value.taxRate,
        discount: rowForm.value.discount,
        preferential: rowForm.value.preferential,
        materialID: rowForm.value.materialID
      }).then(response => {
        getOneUpdate();
        open.value = false;
        proxy.$modal.msgSuccess('修改成功');
      });
    }
  });
}
/** 导出报价 */
function handleSubmitForm() {
  proxy.$modal.loading("正在导出报价，请稍候...");
  const parm = {
    id: data_Id.value,
    items: dataList.value
  }
  proxy.quote_API.DownLoadToExcel(parm).then(response => {
    // 返回的是url
    if (response.code === 1 && response.data) {
      // 创建一个隐藏的a标签用于下载
      const link = document.createElement('a');
      link.href = response.data;
      link.setAttribute('download', `报价单_${dataInfo.value.title1}_${new Date().getTime()}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }).finally(() => {
    setTimeout(() => {
      proxy.$modal.closeLoading();
    }, 500);
  });
}

/** 更新报价 */
function getOneUpdate() {
    proxy.quote_API.UpdateMatAndPriceInquiry(  {
      id: rowForm.value.id,
      materialID: rowForm.value.materialID,
    }).then(response => {
      const oneItem = response.data;
      const index = dataList.value.findIndex(item => item.materialID === oneItem.materialID);
      if (index !== -1) {
        dataList.value[index] = oneItem;
      }
  })
}

/** 查询询价列表 */
function getList() {
  loading.value = true;
  proxy.quote_API.GetOutInquirieslist(queryParams.value).then(response => {
    roleList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    title1: null,
    title2: null,
    title3: null,
    dt1: null,
    dt2: null,
  };
  proxy.resetForm("queryRef");
  handleQuery();
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then(response => {
    menuOptions.value = response.data;
  });
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys();
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    tenantName: null,
    tenantDoMain: null,
    tenantDes: null,
    tenantOrders: 0,
    id: null
  };
  proxy.resetForm("roleRef");
}

/** 添加角色 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加系统";
}

// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);

  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== "2") {
    deptRef.value.setCheckedKeys([]);
  }
}

/** 提交按钮（数据权限） */
function submitDataScope() {
  if (form.value.roleId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openDataScope.value = false;
      getList();
    });
  }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}
getList();
</script>
